import os

import win32gui, win32ui, win32con
from ctypes import windll
from PIL import Image
import cv2
import numpy

def get_list_lpWindowName():
    list_lpWindowName = []
    titles = set()

    def foo(hwnd, nouse):
        # 去掉下面这句就所有都输出了，但是我不需要那么多
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            titles.add(win32gui.GetWindowText(hwnd))

    win32gui.EnumWindows(foo, 0)
    lt = [t for t in titles if t]
    lt.sort()
    for t in lt:
        list_lpWindowName.append(t)
    return list_lpWindowName


if __name__ == '__main__':
    window_values = []
    window_values = get_list_lpWindowName()
    index = 0
    for win in window_values:
        print(index, ":", win)
        index = index + 1
    index = int(input("请输入窗口句柄编号"))

    # 获取后台窗口的句柄，注意后台窗口不能最小化
    hWnd = win32gui.FindWindow(None, str(window_values[index]))
    print("正在获取句柄：" + str(hWnd))
    # 获取句柄窗口的大小信息
    left, top, right, bot = win32gui.GetWindowRect(hWnd)
    width = right - left
    height = bot - top
    print("窗口大小：", width, "x", height)
    # 返回句柄窗口的设备环境，覆盖整个窗口，包括非客户区，标题栏，菜单，边框
    hWndDC = win32gui.GetWindowDC(hWnd)
    # 创建设备描述表
    mfcDC = win32ui.CreateDCFromHandle(hWndDC)
    # 创建内存设备描述表
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建位图对象准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 为bitmap开辟存储空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)
    # 将截图保存到saveBitMap中
    saveDC.SelectObject(saveBitMap)
    # 保存bitmap到内存设备描述表
    saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, "img_Winapi.bmp")
    print("已将窗口截图保存至:" + os.path.join(os.getcwd(), "img_Winapi.bmp"))